package com.shexianyu.simple;

/**
 * @author shexianyu
 * @desc 反转字符串中的单词 III
 * @date 2021/12/3
 */
public class ReverseWords {
    //解法1
    public String reverseWords(String s) {
        //存储结果
        String res = "";
        //根据空格字符将每个单词提取出来
        String[] s1 = s.split(" ");
        for (int i = 0; i < s1.length; i++) {
            String str = s1[i];
            char[] chars = str.toCharArray();
            //将单词字符进行反转
            int n = chars.length;
            for (int j = 0; j < n / 2; j++) {
                char temp = chars[n - j - 1];
                chars[n - j - 1] = chars[j];
                chars[j] = temp;
            }
            //累加每个反转后的单词
            res += new String(chars) + " ";
        }
        //去掉首尾空格
        return res.trim();
    }

    /**
     * 官方解法1
     * 使用额外空间
     *
     * @param s
     * @return
     */
    public String reverseWords1(String s) {
        StringBuffer ret = new StringBuffer();
        int length = s.length();
        int i = 0;
        while (i < length) {
            int start = i;
            while (i < length && s.charAt(i) != ' ') {
                i++;
            }
            for (int p = start; p < i; p++) {
                ret.append(s.charAt(start + i - 1 - p));
            }
            while (i < length && s.charAt(i) == ' ') {
                i++;
                ret.append(' ');
            }
        }
        return ret.toString();
    }




}
